package com.xbao.core.util.token;

import java.util.TreeMap;

import com.xbao.core.util.Md5Encryption;
import com.xbao.core.util.pub.exception.DBExceptionEnums;
import com.xbao.core.util.pub.exception.ServiceException;
import com.xbao.core.util.pub.logger.LogHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;


/**
 * Created by qingshengzheng on 17/12/19.
 */
@Component
public class SignCheck {

	/**
	 *
	 * 校验签名 合法性
	 * 
	 * @param info
	 * @param app_key
	 * @param sign 签名
	 */
	public void checkSign(TreeMap<String, String> map, String app_key, String token, String sign) {
		if (StringUtils.isBlank(app_key)) {
			throw new ServiceException(DBExceptionEnums.SYSTEM__ERROR);
		}
		String t = Md5Encryption.getSign(map, token);
		if (!sign.equals(t)) {
			String paramStr = JSON.toJSONString(map); 
			LogHelper.authKeyLogger().info("{\"params\":{}, \"signContent\":{}, \"rtsign:\":{}}"
					, paramStr, map.get("_authContent"), t);
			throw new ServiceException(DBExceptionEnums.SYSTEM__ERROR);
		}
	}

	/*private <T> String getSignBySecret(CommRequest<Object> query, String app_secret) {
		TreeMap<String, String> map = new TreeMap<String, String>();
		Field[] fields = query.getClass().getDeclaredFields();
		for (Field field : fields) {
			try {
				//ParameterizedType parameterizedType = (ParameterizedType)this.getClass().getGenericSuperclass(); 

				TokenAuth auth = field.getAnnotation(TokenAuth.class);
				String cl = field.getType().getSimpleName();
				String name = field.getName();
				System.out.println("field = "+name + "  bool ="+auth.auth());
				if ("Object".equalsIgnoreCase(cl) && name.equalsIgnoreCase("data")){
					JSONObject obj = JSONObject.parseObject(query.data.toString());
					System.out.println(obj);
				}
				//String v = field.get(query).toString();
				map.put(name, name);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";
	}*/
	

	/*private String getSign(Object o, String app_secret) {
		TreeMap<String, String> map = new TreeMap<String, String>();
		Field[] fields = o.getClass().getDeclaredFields();
		for (Field field : fields) {
			try {
				String cl = field.getType().getSimpleName();
				if (!"String".equalsIgnoreCase(cl))
					continue;
				String name = field.getName();
				String v = field.get(o).toString();
				map.put(name, v);
				String sign = Md5Encryption.getSign(map, app_secret);
				return sign;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";
	}*/

}
